# -*- coding: utf-8 -*-

from odoo import models, fields, api, _
from odoo.exceptions import UserError


class CpqApproval(models.Model):
    _name = 'cpq.approval'
    _description = '报价审批'
    _order = 'sequence, id'
    
    # ============ 基础信息 ============
    quotation_id = fields.Many2one(
        'cpq.quotation',
        string='报价单',
        required=True,
        ondelete='cascade'
    )
    
    sequence = fields.Integer(
        string='顺序',
        default=10
    )
    
    # ============ 审批人 ============
    approver_id = fields.Many2one(
        'res.users',
        string='审批人',
        required=True
    )
    
    role = fields.Selection([
        ('cost_controller', '成本主管'),
        ('sales_manager', '销售经理'),
        ('finance_manager', '财务经理'),
        ('general_manager', '总经理')
    ], string='角色')
    
    # ============ 状态 ============
    state = fields.Selection([
        ('pending', '待审批'),
        ('approved', '已批准'),
        ('rejected', '已拒绝')
    ], string='状态', default='pending', required=True)
    
    # ============ 审批信息 ============
    approval_date = fields.Datetime(
        string='审批时间',
        readonly=True
    )
    
    comments = fields.Text(
        string='审批意见'
    )
    
    # ============ 备注 ============
    notes = fields.Text(
        string='备注'
    )
    
    # ============ 业务方法 ============
    def action_approve(self):
        """批准"""
        for record in self:
            if record.state != 'pending':
                raise UserError('只有待审批的记录才能批准！')
            
            record.write({
                'state': 'approved',
                'approval_date': fields.Datetime.now()
            })
            
            # 发送通知
            record.quotation_id.message_post(
                body=f'{record.approver_id.name} 批准了报价单',
                subject='审批通过',
                message_type='notification',
                subtype_xmlid='mail.mt_comment'
            )
            
            # 检查是否所有审批都通过
            record.quotation_id._check_approval_completion()
    
    def action_reject(self):
        """拒绝"""
        for record in self:
            if record.state != 'pending':
                raise UserError('只有待审批的记录才能拒绝！')
            
            if not record.comments:
                raise UserError('拒绝时必须填写审批意见！')
            
            record.write({
                'state': 'rejected',
                'approval_date': fields.Datetime.now()
            })
            
            # 发送通知
            record.quotation_id.message_post(
                body=f'{record.approver_id.name} 拒绝了报价单\n原因: {record.comments}',
                subject='审批拒绝',
                message_type='notification',
                subtype_xmlid='mail.mt_comment'
            )
            
            # 报价单回退到草稿状态
            record.quotation_id.state = 'draft'
    
    def action_reset(self):
        """重置为待审批"""
        for record in self:
            record.write({
                'state': 'pending',
                'approval_date': False
            })

